package com.yu.blog.interceptor;


import com.yu.blog.annotation.RepeatSubmit;
import com.yu.blog.enums.HttpStatusEnum;
import com.yu.blog.utils.servletUtils.ResponseUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.reflect.Method;

@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod)
        {
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null)
            {
                if (this.isRepeatSubmit(request, annotation))
                {
                    ResponseUtil.setFailedResponse(response, HttpStatusEnum.REPEAT_SUBMIT);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交,由子类实现具体防重复提交的规则
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}
